package ru.spbu.math.android.cbrf.application;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ru.spbu.math.android.cbrf.R;
import ru.spbu.math.android.cbrf.dataprovider.ProviderManager;
import ru.spbu.math.android.cbrf.model.RateType;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;

public class RateTypeListAdapter implements ListAdapter {
	
	private static final String LOG_TAG = "App.RateTypeListAdapter";

	private List<RateType> rateTypes;
	private Context context;
	private Map<RateType, View> views;

	public RateTypeListAdapter(Context context, List<RateType> rateTypes) {
		this.rateTypes = rateTypes;
		this.context = context;

		views = new HashMap<RateType, View>();
		for (RateType rateType : rateTypes) {
			views.put(rateType, makeViewFromRateType(rateType));
		}
	}
	
	public void addRateTypeToList(RateType rateType){
		rateTypes.add(rateType);
	}
	
	public List<RateType> getListRateType(){
		return rateTypes;
	}

	@Override
	public int getCount() {
		return rateTypes.size();
	}

	@Override
	public Object getItem(int position) {
		return rateTypes.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getItemViewType(int position) {
		return ListAdapter.IGNORE_ITEM_VIEW_TYPE;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		return views.get(rateTypes.get(position));
	}

	@Override
	public int getViewTypeCount() {
		return 1;
	}

	@Override
	public boolean hasStableIds() {
		return false;
	}

	@Override
	public boolean isEmpty() {
		return rateTypes.isEmpty();
	}

	@Override
	public void registerDataSetObserver(DataSetObserver observer) {

	}

	@Override
	public void unregisterDataSetObserver(DataSetObserver observer) {

	}

	@Override
	public boolean areAllItemsEnabled() {
		return false;
	}

	@Override
	public boolean isEnabled(int position) {
		return false;
	}

	/**
	 * @param rateType
	 * @return view represent this rateType
	 */
	private View makeViewFromRateType(RateType rateType) {
		View res = LayoutInflater.from(context.getApplicationContext()).inflate(
				R.layout.ratetype_list_item, null);

		ProviderManager provider = ProviderManager.getInstance(context);
		((TextView) res.findViewById(R.id.toptext)).setText(rateType.getName());
		((TextView) res.findViewById(R.id.bottomtext)).setText(provider.getCurrentRate(provider.getExternalIdByRateType(rateType)).getValue() + "");

		return res;
	}
}
